import { defineStore } from 'pinia'
import { constantRoutes, asyncRoutes } from '@/router'

/**
 * 判断用户是否拥有权限访问路由
 * @param {Object} route - 路由对象
 * @param {Array} roles - 用户角色
 * @param {Array} permissions - 用户权限
 * @returns {Boolean}
 */
function hasPermission(route, roles, permissions) {
  // 如果是管理员，拥有所有权限
  if (roles.includes('admin')) return true
  
  // 如果路由定义了roles属性
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  }
  
  // 如果路由定义了permissions属性
  if (route.meta && route.meta.permissions) {
    return permissions.some(permission => {
      if (permission === '*') return true // 通配符表示拥有所有权限
      return route.meta.permissions.includes(permission)
    })
  }
  
  // 如果没有设置权限控制，则默认可以访问
  return true
}

/**
 * 递归过滤异步路由
 * @param {Array} routes - 路由数组
 * @param {Array} roles - 用户角色
 * @param {Array} permissions - 用户权限
 * @returns {Array}
 */
function filterAsyncRoutes(routes, roles, permissions) {
  const res = []
  
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(tmp, roles, permissions)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles, permissions)
      }
      res.push(tmp)
    }
  })
  
  return res
}

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    addRoutes: [],
    roles: [],
    permissions: []
  }),
  
  getters: {
    hasRoles: (state) => state.roles && state.roles.length > 0,
    
    // 检查是否拥有某个角色
    hasRole: (state) => (role) => {
      if (state.roles.includes('admin')) return true
      return state.roles.includes(role)
    },
    
    // 检查是否拥有某个权限
    hasPermission: (state) => (permission) => {
      // 通配符权限检查
      if (state.permissions.includes('*')) return true
      return state.permissions.includes(permission)
    }
  },
  
  actions: {
    // 设置权限列表
    setPermissions(permissions) {
      this.permissions = permissions
    },
    
    // 设置角色列表
    setRoles(roles) {
      this.roles = roles
    },
    
    // 获取权限信息（模拟，实际应该从接口获取）
    async getPermissions() {
      // 从用户信息中获取角色和权限
      const userInfo = JSON.parse(localStorage.getItem('Customer_Churn_UserInfo') || '{}')
      const roles = userInfo.roles || []
      const permissions = userInfo.permissions || []
      
      this.setRoles(roles)
      this.setPermissions(permissions)
      
      return { roles, permissions }
    },
    
    // 生成可访问路由
    generateRoutes(roles, permissions) {
      let accessedRoutes
      
      // 如果是管理员角色，返回所有路由
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        // 根据角色和权限过滤路由
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles, permissions)
      }
      
      this.addRoutes = accessedRoutes
      this.routes = constantRoutes.concat(accessedRoutes)
      
      return accessedRoutes
    }
  }
}) 